package shortcut

import (
	"apibe/single/src/v1/share/croner"
	"apibe/single/src/v1/share/db"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"strconv"
)

type Watch map[string]interface{}

// ApiWatch
// 对所有的已配置接口进行监视
func ApiWatch(status int, apiName string, duration int64) {
	currentHourKey := croner.CurrentHour + "."
	ctx := context.Background()
	opt := &options.UpdateOptions{}
	opt.SetUpsert(true)
	filter := bson.M{"api_name": apiName}
	level := ""
	if duration <= 1*1000000000 {
		level = "<1"
	} else if duration <= 2*1000000000 {
		level = "1-2"
	} else if duration <= 4*1000000000 {
		level = "2-4"
	} else if duration <= 7*1000000000 {
		level = "4-7"
	} else if duration <= 12*1000000000 {
		level = "7-12"
	} else {
		level = ">12"
	}
	levelKey := currentHourKey + "speed." + level
	totalKey := currentHourKey + "total"
	statusKey := currentHourKey + "status." + strconv.Itoa(status)
	update := bson.M{"$inc": bson.M{totalKey: 1, statusKey: 1, levelKey: 1}}
	_, _ = db.GetMongoCollection(db.CollectionDesignWatch).UpdateOne(ctx, filter, update, opt)
}

func GetWatch(apiName string) (map[string]interface{}, error) {
	var watch map[string]interface{}
	err := db.GetMongoCollection(db.CollectionDesignWatch).FindOne(context.Background(), bson.M{"api_name": apiName}).Decode(&watch)
	return watch, err
}
